package cn.lijigou.shopping;


import java.math.BigDecimal;

import org.json.JSONArray;
import org.json.JSONException;

import cn.lijigou.shopping.alipay.Alipay;
import cn.lijigou.shopping.domain.MResult;
import cn.lijigou.shopping.domain.Order;
import cn.lijigou.shopping.domain.Shop;
import cn.lijigou.shopping.service.MSystem;
import cn.lijigou.shopping.util.GetSingleThreadPool;
import cn.lijigou.shopping.util.StringTool;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnDismissListener;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.math.BigDecimal;
import java.util.concurrent.ExecutorService;

public class OrderApprobateActivity extends MActivity implements OnClickListener,OnTouchListener{
	private TextView back= null;
	private LinearLayout titleLeftView= null;
	private TextView register= null;
	private TextView title= null;
	private TextView price = null;
	private TextView total_price = null;
	private LinearLayout layout_coupon_code;
	private TextView textView_coupon_code;
	
	public static Button button_next = null;
	private TextView button_adding = null;
	private TextView button_minus = null;
	
	public  static String  shop_title = null;
	public  TextView  text_shop_name = null;
	public  TextView  text_pay_price = null;
	public  TextView  text_shop_size = null;
	public  TextView  text_buyTip= null;
	public  TextView  text_shop_mobile = null;
	
	private EditText order_mobile = null;
	private TextView order_size = null;
	private TextView order_receiver_name = null;
	private TextView order_receiver_address = null;
	public TextView payTip = null;
	private String pay_tip = "";
	private InputMethodManager imm=null;
	private Order order = null;
	private Shop shop = null;
	private int size;
	public static String mobile = "";
	public static String receiver_name = "";
	public static String receiver_address = "";
	public static String leave_msg;
	public static String o_size;
	public  static Dialog mDialog;
	public  static Dialog mCouponDialog;
	public  Button mBankCard;
	public  Button mAlipay;
	public  ProgressBar mProgressBar;
	private Boolean isFlower;
//	private static EditText mEditText_Name;
//	private static EditText mEditText_Address;
	private static EditText mEditText_Msg;
	private EditText mEdit_Coupon;
	private String mCouponCode = "";
	private LinearLayout mLayout_CouponProgress;
	private String mCouponCodeMoney = "0";
	private MResult mResult;
	
	private BigDecimal shopprice = new BigDecimal("0");
	private BigDecimal count = new BigDecimal("0");
	private BigDecimal couponMoney = new BigDecimal("0");
	private BigDecimal totalprice = new BigDecimal("0");
	private ExecutorService executorService = GetSingleThreadPool.getInstance();
	
	public Handler updateHandler = new Handler(){
		public void handleMessage(Message msg) {
			if(msg.what==1){
				mCouponDialog.dismiss();
				textView_coupon_code.setText(mCouponCodeMoney);
				shopprice = new BigDecimal(shop.getPrice());
				count = new BigDecimal(order_size.getText().toString());
				couponMoney = new BigDecimal(mCouponCodeMoney);
				totalprice = shopprice.multiply(count).subtract(couponMoney);
				total_price.setText(totalprice.toString());
			}else if(msg.what==0){
				mCouponDialog.dismiss();
				String mError = mResult.getInfo();
				Toast.makeText(OrderApprobateActivity.this, mError, 1).show();
			}
		};
	};
		
	
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.alipay_go);
		overridePendingTransition(R.anim.push_in,R.anim.push_out);
		shop = (Shop)this.getIntent().getSerializableExtra("shop");
		isFlower = this.getIntent().hasExtra("flower");
		setViews();
		setOnClickListeners();
		
		ShopDetailActivity.mList.add(this);
		if(ShopDetailActivity.buy !=null ){
			ShopDetailActivity.buy.setEnabled(true);
		}
		if(BuySiteDetailActivity.buy !=null ){
			BuySiteDetailActivity.buy.setEnabled(true);
		}
		if(TodayDetailActivity.buy !=null ){
			TodayDetailActivity.buy.setEnabled(true);
		}
		if(OrderDetailShopActivity.buyOne !=null ){
			OrderDetailShopActivity.buyOne.setEnabled(true);
		}
        if(PushDetailShopActivity.buyOne !=null ){
			PushDetailShopActivity.buyOne.setEnabled(true);
		}
		
	}
	
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onPause();
		if(mDialog != null && mDialog.isShowing()){
			mDialog.dismiss();
		}
	}
	private void setViews() {
		order_size = (TextView) findViewById(R.id.order_size);
		order_receiver_name = (TextView) findViewById(R.id.receiver_name);
		order_receiver_address = (TextView) findViewById(R.id.receiver_address);
		mEditText_Msg = (EditText) this.findViewById(R.id.leave_msg);
		order_mobile = (EditText) findViewById(R.id.order_mobile);
		
		if(isFlower){
			findViewById(R.id.layout_name).setVisibility(View.VISIBLE);
			findViewById(R.id.layout_address).setVisibility(View.VISIBLE);
		}
		
		back = (TextView) this.findViewById(R.id.title_btn_left);
		titleLeftView = (LinearLayout) this.findViewById(R.id.titleLeftView);
		back.setBackgroundResource(R.drawable.title_back_normal);
		register = (TextView) this.findViewById(R.id.title_btn_right);
		register.setVisibility(View.GONE);
		title = (TextView) this.findViewById(R.id.text_center);
		title.setText(R.string.submit_order);
		findViewById(R.id.titleRightView).setVisibility(View.GONE);
		
		price = (TextView) this.findViewById(R.id.textview_product_price);
		price.setText(shop.getPrice());
		total_price = (TextView) this.findViewById(R.id.textview_product_total_price);
		total_price.setText(shop.getPrice());

		layout_coupon_code = (LinearLayout) this.findViewById(R.id.coupon_code);
		textView_coupon_code = (TextView) this.findViewById(R.id.textview_coupon);
		
		button_next = (Button)findViewById(R.id.button_next);
		button_next.setOnTouchListener(this);
		button_adding = (TextView)findViewById(R.id.button_adding);
		button_minus = (TextView)findViewById(R.id.button_minus);
		
		
		
		
		SharedPreferences sp = OrderApprobateActivity.this.getSharedPreferences("user", Context.MODE_WORLD_READABLE);
		mobile = sp.getString("phoneNum", "");
		if(!mobile.equals("")){
			order_mobile.setText(mobile);
		}
	}
	private void  setOnClickListeners(){
		button_next.setOnClickListener(this);
		order_mobile.setOnClickListener(this);
		button_adding.setOnClickListener(this);
		button_minus.setOnClickListener(this);
		titleLeftView.setOnClickListener(this);
		layout_coupon_code.setOnClickListener(this);
	}
	
	public void onClick(View v) {
		MSystem.pv +=1;
		switch (v.getId()) {
			case R.id.titleLeftView:
				if(ShopDetailActivity.mList.contains(this)){
					ShopDetailActivity.mList.remove(this);
				}
				if(imm!=null){
	            	imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); 
	            }
				this.finish();
			break;
			case R.id.button_next:
				button_next.setEnabled(false);
				//保存虚拟账号
            	mobile = order_mobile.getText().toString();
            	o_size = order_size.getText().toString();
            	receiver_name = order_receiver_name.getText().toString();
            	receiver_address = order_receiver_address.getText().toString();
            	leave_msg = mEditText_Msg.getText().toString();
            	
            	if(StringTool.isNull(mobile)){
            		button_next.setEnabled(true);
            		Toast.makeText(OrderApprobateActivity.this, R.string.error_phonenum_null, 1).show();
            	}else if(!StringTool.isMobileNO(mobile)){
            		button_next.setEnabled(true);
            		Toast.makeText(OrderApprobateActivity.this, R.string.error_phonenum_format, 1).show();
            	}else if("0".equals(o_size)){
            		button_next.setEnabled(true);
            		Toast.makeText(OrderApprobateActivity.this, R.string.error_count_num, 1).show();
            	}else if("".equals(o_size)){
            		button_next.setEnabled(true);
            		Toast.makeText(OrderApprobateActivity.this, R.string.error_count_num_null, 1).show();
            	}else if(isFlower == true && StringTool.isNull(receiver_name)){
            		button_next.setEnabled(true);
            		Toast.makeText(OrderApprobateActivity.this, R.string.error_receiver_name_null, 1).show();
            	}else if(isFlower == true && StringTool.isNull(receiver_address)){
            		button_next.setEnabled(true);
            		Toast.makeText(OrderApprobateActivity.this, R.string.error_receiver_address_null, 1).show();
            	}else{
            		shopprice = new BigDecimal(shop.getPrice());
    				count = new BigDecimal(order_size.getText().toString());
    				couponMoney = new BigDecimal(mCouponCodeMoney);
    				totalprice = shopprice.multiply(count).subtract(couponMoney);
    				
            		Intent mIntent = new Intent(this, ConfirmOrderActivity.class);
            		mIntent.putExtra("shop", shop);
            		mIntent.putExtra("mTotalprice", totalprice.toString());
            		mIntent.putExtra("mCouponCodeMoney", mCouponCodeMoney);
            		if(isFlower){
            			mIntent.putExtra("flower", true);
					}
            		
            		startActivity(mIntent);
            		
	    	    	SharedPreferences sp = OrderApprobateActivity.this.getSharedPreferences("user", Context.MODE_PRIVATE);
					Editor edit = sp.edit();
					edit.putString("phoneNum",mobile);
					edit.commit();
            	}
            	
				break;
			case R.id.button_adding:
				int size_a = 0;
				if(!"".equals(order_size.getText().toString())){
					size_a =Integer.parseInt(order_size.getText().toString());
				}
				size_a++;
				order_size.setText(size_a+"");
				shopprice = new BigDecimal(shop.getPrice());
				count = new BigDecimal(order_size.getText().toString());
				couponMoney = new BigDecimal(mCouponCodeMoney);
				totalprice = shopprice.multiply(count).subtract(couponMoney);
//				total_price.setText(""+((Float.parseFloat(shop.getPrice())*Integer.parseInt(order_size.getText().toString())) - Float.parseFloat(mCouponCodeMoney)));
				total_price.setText(totalprice.toString());
				break;
			case R.id.button_minus:
				int size_m = 0;
				if(!"".equals(order_size.getText().toString())){
					size_m =Integer.parseInt(order_size.getText().toString());
				}
				size_m--;
				if(size_m>0){
					order_size.setText(size_m+"");
				}
				shopprice = new BigDecimal(shop.getPrice());
				count = new BigDecimal(order_size.getText().toString());
				couponMoney = new BigDecimal(mCouponCodeMoney);
				totalprice = shopprice.multiply(count).subtract(couponMoney);
//				total_price.setText(""+((Float.parseFloat(shop.getPrice())*Integer.parseInt(order_size.getText().toString()))- Float.parseFloat(mCouponCodeMoney)));
				total_price.setText(totalprice.toString());
				break;
			case R.id.order_mobile:
//				v.setFocusable(true);
//				v.requestFocusFromTouch();
				break;
			case R.id.coupon_code:
				
				showCouponDialog();
				break;
		 
		}
	}
	
	
	
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub\
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			if(v.getId() == button_next.getId()){
				button_next.setTextColor(Color.WHITE);
				button_next.setBackgroundResource(R.drawable.buy_btn_pressed);
			}
			
			break;
		case MotionEvent.ACTION_UP:
			if(v.getId() == button_next.getId()){
				button_next.setTextColor(Color.BLACK);
				button_next.setBackgroundResource(R.drawable.buy_btn_normal);
			}
			break;

		default:
			break;
		}

		return false;
	}
	private void showCouponDialog() {
		LayoutInflater factory=LayoutInflater.from(OrderApprobateActivity.this);
		final View v1=factory.inflate(R.layout.confirm_coupon_code,null);
		mEdit_Coupon = (EditText) v1.findViewById(R.id.tv_coupon_code);
		
		
		mCouponDialog = new Dialog(OrderApprobateActivity.this,android.R.style.Theme_Translucent_NoTitleBar);
		mCouponDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
                WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
		mCouponDialog.setContentView(v1);
 
		mLayout_CouponProgress = ((LinearLayout) mCouponDialog.findViewById(R.id.layout_progressBar_wait));
		
		((Button) mCouponDialog.findViewById(R.id.ok))
				.setOnClickListener(new OnClickListener() {

					
			public void onClick(View v) {
				// write your code to do things after users clicks CANCEL
				mLayout_CouponProgress.setVisibility(View.VISIBLE);
				mCouponDialog.setContentView(v1);

				mCouponCode = mEdit_Coupon.getText().toString();
				executorService.execute(new Thread() {
					public void run() {
						mResult = MSystem.confirm_Coupon_Code(mCouponCode, order_size.getText().toString(), shop.getId());

						if (mResult != null && mResult.isSuccess()) {
							try {
								mCouponCodeMoney = new JSONArray("[" + mResult.getData() + "]").getJSONObject(0).getString("money");
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							updateHandler.sendEmptyMessage(1);

						} else {
							updateHandler.sendEmptyMessage(0);

						}

					}
				});
			}
				});
		((Button) mCouponDialog.findViewById(R.id.cancel))
				.setOnClickListener(new OnClickListener() {

					
					public void onClick(View v) {
						mCouponDialog.dismiss();
					}
				});
		setShadow(true);
		mCouponDialog.getWindow().setWindowAnimations(R.style.dialogWindowAnim);
//		mCouponDialog.getWindow().setBackgroundDrawableResource(R.color.vifrification);
		mCouponDialog.show();
		
		mCouponDialog.setOnDismissListener(new OnDismissListener() {
			
			public void onDismiss(DialogInterface dialog) {
				// TODO Auto-generated method stub
				setShadow(false);
			}
		});
	}
	
	public void setShadow(Boolean isTransparent){
		WindowManager.LayoutParams lp=getWindow().getAttributes();
		if(isTransparent){
	        lp.alpha=0.3f;
	        lp.dimAmount=0.3f;
	        getWindow().setAttributes(lp);
	        getWindow().setAttributes(lp);
//	        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
		}else{
			lp.alpha=1.0f;
	        lp.dimAmount=1.0f;
	        getWindow().setAttributes(lp);
	        getWindow().setAttributes(lp);
		}

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			button_next.setEnabled(true);
			if(ShopDetailActivity.mList.contains(this)){
				ShopDetailActivity.mList.remove(this);
			}
            if(imm!=null){
            	imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); 
            }
			this.finish();
			return true;
		}

		return false;
	}
	
//	public void setDate(View v1){
//		text_shop_name = (TextView) v1.findViewById(R.id.text_shop_name);
//		text_pay_price = (TextView) v1.findViewById(R.id.text_pay_price);
//		text_shop_size = (TextView) v1.findViewById(R.id.text_shop_size);
//		text_shop_mobile = (TextView) v1.findViewById(R.id.text_shop_mobile);
//		
//		size = Integer.parseInt(order_size.getText().toString());
//		mobile = order_mobile.getText().toString();
//		if(isFlower){
//			receiver_name = mEditText_Name.getText().toString();
//			receiver_address = mEditText_Address.getText().toString();
//			leave_msg = mEditText_Msg.getText().toString();
//		}
//		shop_title = getResources().getString(R.string.product_name) + "【"+shop.getSource()+"】" + shop.getInfo();
//		text_shop_name.setText(getResources().getString(R.string.product_name) + "【"+shop.getSource()+"】" + shop.getInfo());
////		text_pay_price.setText(getResources().getString(R.string.amount_payable) + "" + Float.parseFloat(shop.getPrice())*size);
//		shopprice = new BigDecimal(shop.getPrice());
//		count = new BigDecimal(order_size.getText().toString());
//		couponMoney = new BigDecimal(mCouponCodeMoney);
//		text_pay_price.setText(getResources().getString(R.string.amount_payable) + "" + shopprice.multiply(count).subtract(couponMoney));
//		text_shop_size.setText(getResources().getString(R.string.buy_count) + size);
//		text_shop_mobile.setText(getResources().getString(R.string.phone_num) + mobile);
//	}
}
